package com.ncmmall.mall.controller.business.order;

import com.ncmmall.application.business.order.OrderAfterSaleApplication;
import com.feijin.commons.excel.ExcelExports;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.lang.Dates;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.order.aftersale.OrderAfterSale;
import com.ncmmall.domain.business.order.aftersale.QOrderAfterSale;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 售后订单管理
 *
 * @author linxs
 * @date 2019-07-10 17:44
 */
@Controller
@RequestMapping(value = "/merchant/orderaftersale")
public class MerchantOrderAfterSaleController {

    private final static Logger logger = LoggerFactory.getLogger(MerchantOrderAfterSaleController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private OrderAfterSaleApplication afterSaleApplication;

    /**
     * 订单列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, OrderAfterSale order) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = new HashMap<>();
        params.put("id", Securitys.currentUser().getId());

        String hql = builderSQL("select u from OrderAfterSale u where u.merchant.id = :id ", params, order);
        QueryPage<OrderAfterSale> page = queryChannelService.findPage(hql, pageRequest.setParams(params), OrderAfterSale.class);
        model.addAttribute("page", page).addAttribute("params", order);
        return "merchant/order/aftersale/list";
    }

    /**
     * 导出Excel
     */
    @RequestMapping(value = "/exports", method = RequestMethod.GET)
    private void exports(HttpServletRequest request, HttpServletResponse response, OrderAfterSale order) {
        try {
            Map<String, Object> params = Maps.newHashMap();
            params.put("id", Securitys.currentUser().getId());

            String sql = "select u from OrderAfterSale u where u.merchant.id = :id ";
            String hql = builderSQL(sql, params, order);

            List<OrderAfterSale> result = queryChannelService.findAll(hql, params, OrderAfterSale.class);
            Map<String, Object> data = ImmutableMap.of("result", result);
            ExcelExports document = new ExcelExports.Templates().formTemplate("merchantAfterSaleOrders.ftl").bind(data).store("merchantAfterSaleOrders.xls").build();

            document.generate();
            Webs.download(request, response, document.getFile(), "售后订单" + Dates.transDateToStr(new Date()) + ".xls");
        } catch (Exception e) {
            logger.error("[导出异常]", e);
        }
    }


    /**
     * 查看详情
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {

        OrderAfterSale afterSale = queryChannelService.findOne(QOrderAfterSale.orderAfterSale.id.eq(id), OrderAfterSale.class);
        List<Goods> giftGoodses = Lists.newArrayList();

        //赠品活动订单
        if (afterSale.getOrder().getMarketingType() == 1) {
            giftGoodses = queryChannelService.findAll("select g.goods from GiftGoods g where g.gift.id = :id ", ImmutableMap.of("id", afterSale.getOrder().getGiftActivity().getId()), Goods.class);
        }

        model.addAttribute("giftgoodses", giftGoodses);
        model.addAttribute("afterSale", afterSale);
        return "merchant/order/aftersale/detail";
    }


    /**
     * 审核
     */
    @RequestMapping(value = "/{id}/check", method = RequestMethod.GET)
    private String check(Model model, @PathVariable("id") long id) {
        OrderAfterSale afterSale = queryChannelService.findOne(QOrderAfterSale.orderAfterSale.id.eq(id), OrderAfterSale.class);
        model.addAttribute("afterSale", afterSale);
        return "merchant/order/aftersale/check";
    }

    /**
     * 审核售后订单申请
     */
    @RequestMapping(value = "/{id}/check", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> check(@RequestHeader("X-Requested-With") String requestWith, @ModelAttribute OrderAfterSale afterSale) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be ajax !");
            }
            afterSaleApplication.check(afterSale);
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[售后审核异常]", e);
            return ImmutableMap.of("status", false, "message", "售后审核异常");
        }
    }

    /**
     * 商家签收
     */
    @RequestMapping(value = "/signFor", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> signFor(@RequestHeader("X-Requested-With") String requestWith, @ModelAttribute OrderAfterSale afterSale) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be ajax !");
            }
            afterSaleApplication.signFor(afterSale);
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[商家签收售后订单异常]", e);
            return ImmutableMap.of("status", false, "message", "签收异常");
        }
    }


    /**
     * 退款
     */
    @RequestMapping(value = "/refund", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> refund(@RequestHeader("X-Requested-With") String requestWith, @ModelAttribute OrderAfterSale afterSale) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be ajax !");
            }
            afterSaleApplication.refund(afterSale);
            return ImmutableMap.of("status", true);
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            logger.error("[商家签收售后订单异常]", e);
            return ImmutableMap.of("status", false, "message", "退款失败，请联系平台");
        }
    }


    /**
     * 条件筛选
     */
    private String builderSQL(String sql, Map<String, Object> params, OrderAfterSale order) {

        if (null != order.getOrder() && !Strings.isNullOrEmpty(order.getOrder().getOrderNo())) {
            sql += " and u.order.orderNo like :no ";
            params.put("no", "%" + order.getOrder().getOrderNo() + "%");
        }

        if (order.getMember() != null && order.getMember().getId() > 0) {
            sql += " and u.member.id = :memberId ";
            params.put("memberId", order.getMember().getId());
        }

        if (order.getCheckStatus() > 0) {
            sql += " and u.checkStatus = :status ";
            params.put("status", order.getCheckStatus());
        }

        if (!Strings.isNullOrEmpty(order.getBeginTime())) {
            sql += " and u.createTime >= :btime ";
            params.put("btime", Timestamp.valueOf(order.getBeginTime() + " 00:00:00"));
        }

        if (!Strings.isNullOrEmpty(order.getEndTime())) {
            sql += " and u.createTime <= :etime ";
            params.put("etime", Timestamp.valueOf(order.getEndTime() + " 23:59:59"));
        }

        return sql + " order by u.createTime desc ";
    }

}
